//
//  SEDoctorListViewController.swift
//  SmartEyeForPatient
//
//  Created by QDSG on 2021/4/6.
//

import UIKit

enum SEDoctorListFromType {
    case hospitalize
    case department
    
    var title: String {
        switch self {
        case .hospitalize:
            return "线上问诊"
        case .department:
            return "医生列表"
        }
    }
}

class SEDoctorListViewController: SEBaseViewController {
    
    private var fromType: SEDoctorListFromType = .hospitalize
    
    private var viewModel = SEDoctorViewModel()
    
    private var filterMenuModel = SEFilterMenuModel()
    
    convenience init(fromType: SEDoctorListFromType, departmentId: String = "", hospitalId:String = "", examineRecordVm: SEExamineRecordViewModel = SEExamineRecordViewModel(), patientInfo: SEPatientDetailViewModel = SEPatientDetailViewModel()) {
        self.init()
        self.fromType = fromType
        self.title = fromType.title
        self.viewModel.departmentId = departmentId
        self.viewModel.hospitalId = hospitalId
        self.viewModel.examineRecordVm = examineRecordVm
        self.viewModel.patientInfo = patientInfo
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        viewModel.updateData = { [weak self] status in
            self?.endRefreshing()
            switch status {
            case .success:
                self?.tableView.reloadData()
            case .auth:
                self?.presentLoginViewController(selector: #selector(self?.loadData(more:)))
            case .failure(let msg):
                SEHUD.showError(message: msg)
            }
        }
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        searchBarBecomeFirstResponse(searchBar)
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        searchBarResignFirstResponse(searchBar)
    }

    
    override func setupUI() {
        tableView.se_header = SERefreshHeader { [weak self] in self?.loadData(more: false) }
        tableView.se_header?.beginRefreshing()
        tableView.se_footer = SERefreshFooter { [weak self] in self?.loadData(more: true) }
    }

    @IBOutlet weak var searchBar: UISearchBar! {
        didSet {
            searchBar.delegate = self
        }
    }
    
    @IBOutlet private weak var filterHeader: SEFilterHeader! {
        didSet {
            filterHeader.delegate = self
            filterHeader.leftButton.layoutButton(with: .imageRight)
            filterHeader.centerButton.layoutButton(with: .imageRight)
            filterHeader.rightButton.layoutButton(with: .imageRight)
        }
    }
    
    @IBOutlet private weak var tableView: UITableView! {
        didSet {
            tableView.backgroundColor = UIColor.background
            tableView.tableFooterView = UIView()
            tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: UIScreen.bottomSafeHeight, right: 0)
            tableView.estimatedRowHeight = 102
            tableView.rowHeight = UITableView.automaticDimension
            
            tableView.register(SEDoctorListCell.nibForCell(), forCellReuseIdentifier: SEDoctorListCell.reuseIdentifier())
        }
    }
    
    private weak var filterMenu: SEFilterHeaderMenuView?

    func searchBarBecomeFirstResponse(_ searchBar: UISearchBar) {
        if !(searchBar.text?.isEmpty ?? true) {
            searchBar.becomeFirstResponder()
            navigationController?.setNavigationBarHidden(true, animated: true)
        }
    }

    func searchBarResignFirstResponse(_ searchBar: UISearchBar) {
        searchBar.resignFirstResponder()
        searchBar.showsCancelButton = false
        navigationController?.setNavigationBarHidden(false, animated: true)
    }
}

// MARK: - SEFilterHeaderDelegate

extension SEDoctorListViewController: SEFilterHeaderDelegate {
    func showFilterMenu(_ header: SEFilterHeader, didClicked sender: UIButton) {
        let filterType = SEFilterHeaderFilterType(rawValue: sender.tag - header.btnTag) ?? .unknown
        switch filterType {
        case .unknown:
            break
        default:
            if sender.isSelected {
                filterMenu = UINib.loadViewFrom(SEFilterHeaderMenuView.self)
                filterMenu?.showMenu(in: view, rect: header.frame, menuStyle: filterType.menuStyle)
                filterMenu?.filterMenuClosure = { model in
                    self.filterMenuModel = model
                    header.reset(sender, title: model.title)
                }
            } else {
                filterMenu?.dismissMenu()
            }
        }
    }
}

extension SEDoctorListViewController {
    @objc private func loadData(more: Bool) {
        viewModel.getDoctorListOfOnlineInquiry(loadMore: more)
    }
    
    private func endRefreshing() {
        tableView.endHeaderRefreshing()
        tableView.endFooterRefreshing(hasMore: viewModel.hasMore)
    }
}

// MARK: - UITableViewDataSource

extension SEDoctorListViewController: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return viewModel.numberOfSections
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: SEDoctorListCell.reuseIdentifier()) as! SEDoctorListCell
        cell.update(with: viewModel.viewModel(at: indexPath))
        return cell
    }
}

// MARK: - UITableViewDelegate

extension SEDoctorListViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: false)
        
        let vm = viewModel.viewModel(at: indexPath)
        
        switch fromType {
        case .hospitalize: pushToOnlineReserveVc(vm)
        case .department: pushToDoctorDetailVc(vm)
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 1
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.0001
    }
}

// MARK: - push & click event

extension SEDoctorListViewController {
    private func pushToOnlineReserveVc(_ vm: SEDoctorDetailViewModel) {
        let onlineReserveVc = SEOnlineReserveViewController(doctorDetailVM: vm, examineRecordVm: viewModel.examineRecordVm, patientInfo: viewModel.patientInfo)
        onlineReserveVc.title = "就诊信息填写"
        navigationController?.pushViewController(onlineReserveVc, animated: true)
    }
    
    private func pushToDoctorDetailVc(_ vm: SEDoctorDetailViewModel) {
        let doctorDetailVc = SEDoctorDetailViewController(with: vm.model.id ?? "")
        doctorDetailVc.title = "医生详情"
        navigationController?.pushViewController(doctorDetailVc, animated: true)
    }
}

// MARK: - UISearchBarDelegate

extension SEDoctorListViewController: UISearchBarDelegate {
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        view.endEditing(true)
        let cancelBtn = searchBar.value(forKey: "cancelButton") as? UIButton
        cancelBtn?.isEnabled = true
        viewModel.doctorName = searchBar.text!
        loadData(more: false)
    }

    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        view.endEditing(true)
        searchBar.text = ""
        searchBar.setShowsCancelButton(false, animated: true)
        navigationController?.setNavigationBarHidden(false, animated: true)
        viewModel.doctorName = searchBar.text!
        loadData(more: false)
    }

    func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
        searchBar.setShowsCancelButton(true, animated: true)
        navigationController?.setNavigationBarHidden(true, animated: true)
    }

    func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {

    }
}
